'''
mangrove.py
Default install & search achieve.
'''
from magv.download_source_support import gitrepo
import json
import os
from magv import get_local_name

def download(path, ext, branch, repo, config):
    try:
        with open(os.path.join(config.config_path, repo, "extension", ext, "describle.json"), "r") as f:
            dist = json.loads(f.read())
            f.close()
    except Exception:
        config.logger.error("Extension not found")
        raise Exception("Extension not found")
    try:
        gitrepo.download(path, dist["repo"], branch, config)
        with open(os.path.join(path, ".REQUIREMENTS"), "w+") as f:
            f.write(str(dist["requirements_software_tips"]))
            f.close()
    except Exception as e:
        config.logger.error("An error occured while downloading extension")
        config.logger.error(e)
        raise e

def search(ext, config):
    try:
        for repodir in config.repo_path:
            dist = os.listdir(repodir + '/extension')
            res = list()
            for i in dist:
                if not i.find(ext) == -1:
                    with open(os.path.join(repodir + '/extension/' + ext, 'describle.json'), "r") as f:
                        item = json.loads(f.read())
                        f.close()
                        res.append([i.rsplit(".", 1)[0], "MANGROVE", get_local_name(repodir + "."), item["introduce"]]) # Strip the ".json" part
    except Exception as e:
        config.logger.error("An error occured while searching extension")
        raise e
    return res